package gold.digger;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC686 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int repeatedStringMatch(String a, String b) {
            if (a.contains(b)) return 1;

            if ((a + a).contains(b)) {
                return 2;
            }

            int splitPos = b.indexOf(a), count = 0;
            if (splitPos < 0) {
                if (a.contains(b) && a.length() - a.lastIndexOf(b) == b.length()) return 1;
                if (a.contains(b) && a.indexOf(b) == 0) return 1;
                return -1;
            }

            while (b.contains(a)) {
                if (splitPos != b.indexOf(a)) return -1;
                b = b.replaceFirst(a, "");
                ++count;
            }

            if (count > 0 && b.length() <= 0) return count;
            String pre = b.substring(0, splitPos), af = b.substring(splitPos, b.length());
            if (pre.length() > 0 && af.length() > 0) {
                if (a.contains(pre) && (a.length() - a.lastIndexOf(pre) == pre.length()) && a.indexOf(af) == 0)
                    return count + 2;
            }

            if (pre.length() > 0 && a.contains(pre) && (a.length() - a.indexOf(pre) == pre.length())) return count + 1;
            if (af.length() > 0 && a.indexOf(af) == 0) return count + 1;
            if (pre.length() <= 0 && af.length() <= 0) return count;

            return -1;
        }
    }

    public void run() {
        Solution solution = new Solution();
//        System.out.println(solution.repeatedStringMatch("abcd", "cdabcdab"));
//        System.out.println(solution.repeatedStringMatch("a", "aa"));
//        System.out.println(solution.repeatedStringMatch("a", "a"));
//        System.out.println(solution.repeatedStringMatch("abc", "wxyz"));
        System.out.println(solution.repeatedStringMatch("baa", "abaab"));
    }

    public static void main(String[] args) throws Exception {
        LC686 an = new LC686();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
